import torch
import torch.nn as nn
import torch.nn.functional as F
from torchvision import transforms, datasets
from torch.utils.data import DataLoader

# MLP 模型定义
class MLP(nn.Module):
    def __init__(self, input_size, hidden1, hidden2, num_classes):
        super(MLP, self).__init__()
        self.fc1 = nn.Linear(input_size, hidden1)
        self.relu1 = nn.ReLU()
        self.fc2 = nn.Linear(hidden1, hidden2)
        self.relu2 = nn.ReLU()
        self.fc3 = nn.Linear(hidden2, num_classes)

    def forward(self, x):
        out = self.relu1(self.fc1(x))
        out = self.relu2(self.fc2(out))
        out = self.fc3(out)
        return out

# 数据预处理
transform = transforms.Compose([
    transforms.Resize((224, 224)),  # 将图片统一缩放到224x224
    transforms.ToTensor(),
    transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))
])

# 加载数据集
train_dataset = datasets.ImageFolder(root=r'D:\develop\PythonCode\python基础\附_项目实战\九_薄膜图片级别分类\lab3_MLP\data\train', transform=transform)
test_dataset = datasets.ImageFolder(root=r'D:\develop\PythonCode\python基础\附_项目实战\九_薄膜图片级别分类\lab3_MLP\data\test', transform=transform)

train_loader = DataLoader(dataset=train_dataset, batch_size=2, shuffle=True)
test_loader = DataLoader(dataset=test_dataset, batch_size=1, shuffle=False)

# 设备配置
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')

# 模型初始化
input_size = 224 * 224 * 3  # 对于彩色图像，输入大小
hidden1 = 512
hidden2 = 256
num_classes = 3
model = MLP(input_size, hidden1, hidden2, num_classes).to(device)

# 损失函数和优化器
criterion = nn.CrossEntropyLoss()
optimizer = torch.optim.Adam(model.parameters(), lr=0.001)

# 训练模型
best_accuracy = 0.0
num_epochs = 100
for epoch in range(num_epochs):
    model.train()
    for images, labels in train_loader:
        images = images.view(-1, 224*224*3).to(device)
        labels = labels.to(device)

        outputs = model(images)
        loss = criterion(outputs, labels)

        optimizer.zero_grad()
        loss.backward()
        optimizer.step()

    # 测试模型
    model.eval()
    with torch.no_grad():
        correct = 0
        total = 0
        for images, labels in test_loader:
            images = images.view(-1, 224*224*3).to(device)
            labels = labels.to(device)
            outputs = model(images)
            _, predicted = torch.max(outputs.data, 1)
            total += labels.size(0)
            correct += (predicted == labels).sum().item()

        accuracy = 100 * correct / total
        print(f'Epoch [{epoch+1}/{num_epochs}], Loss: {loss.item():.4f}, Accuracy: {accuracy:.2f}%')

        # 保存最好的模型
        if accuracy >= best_accuracy:
            best_accuracy = accuracy
            torch.save(model.state_dict(), 'mlp_best_model.pth')
            print("Saved Best Model with Accuracy: {:.2f}%".format(accuracy))
